﻿using MQTTnet;
using MQTTnet.Core;
using MQTTnet.Core.Client;
using MQTTnet.Core.Packets;
using MQTTnet.Core.Protocol;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MQTTnet_Client
{
    class Program
    {

        private static MqttClient mqttClient = null;

        static void Main(string[] args)
        {
            Task.Run(async () => { await ConnectMqttServerAsync(); });
            Console.ReadKey();
        }


        private static async Task ConnectMqttServerAsync()
        {
            if (mqttClient == null)
            {
                mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient;
                mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
                mqttClient.Connected += MqttClient_Connected;
                mqttClient.Disconnected += MqttClient_Disconnected;
            }

            try
            {
                var options = new MqttClientTcpOptions
                {
                    Server = "127.0.0.1",
                    ClientId = Guid.NewGuid().ToString().Substring(0, 5),
                    UserName = "u001",
                    Password = "p001",
                    CleanSession = true
                };

                await mqttClient.ConnectAsync(options);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"连接到MQTT服务器失败！" + Environment.NewLine + ex.Message + Environment.NewLine);
            }
        }
        private static void MqttClient_Connected(object sender, EventArgs e)
        {

            Console.WriteLine("已连接到MQTT服务器！" + Environment.NewLine);
        }

        private static void MqttClient_Disconnected(object sender, EventArgs e)
        {
            Console.WriteLine("已断开MQTT连接！" + Environment.NewLine);
        }

        private static void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            Console.WriteLine($">> {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");
        }


        //订阅主题
        private void Sub(string name)
        {
            string topic = name;

            if (string.IsNullOrEmpty(topic))
            {
                Console.WriteLine("订阅主题不能为空！");
                return;
            }

            if (!mqttClient.IsConnected)
            {
                Console.WriteLine("MQTT客户端尚未连接！");
                return;
            }

            mqttClient.SubscribeAsync(new List<TopicFilter> {
                new TopicFilter(topic, MqttQualityOfServiceLevel.AtMostOnce)
            });

            Console.WriteLine($"已订阅[{topic}]主题" + Environment.NewLine);
        }



        //private void BtnSubscribe_ClickAsync(object sender, EventArgs e)
        //{
        //    string topic = txtSubTopic.Text.Trim();

        //    if (string.IsNullOrEmpty(topic))
        //    {
        //        MessageBox.Show("订阅主题不能为空！");
        //        return;
        //    }

        //    if (!mqttClient.IsConnected)
        //    {
        //        MessageBox.Show("MQTT客户端尚未连接！");
        //        return;
        //    }

        //    mqttClient.SubscribeAsync(new List<TopicFilter> {
        //        new TopicFilter(topic, MqttQualityOfServiceLevel.AtMostOnce)
        //    });

        //    txtReceiveMessage.AppendText($"已订阅[{topic}]主题" + Environment.NewLine);
        //    txtSubTopic.Enabled = false;
        //    btnSubscribe.Enabled = false;
        //}


        //发布主题

        private void Pub(string name,string message)
        {
            string topic = name;

            if (string.IsNullOrEmpty(topic))
            {
                Console.WriteLine("发布主题不能为空！");
                return;
            }
            //发送消息
            string inputString = message;
            var appMsg = new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes(inputString), MqttQualityOfServiceLevel.AtMostOnce, false);
            mqttClient.PublishAsync(appMsg);
        }
    }
}
